package cn.cdliux.spring.context.support;

import cn.cdliux.spring.beans.BeansException;
import cn.cdliux.spring.beans.factory.ConfigureableListableBeanFactory;
import cn.cdliux.spring.beans.factory.config.BeanFactoryPostProcessor;
import cn.cdliux.spring.beans.factory.config.BeanPostProcessor;
import cn.cdliux.spring.context.ConfigurableApplicationContext;
import cn.cdliux.spring.core.io.DefaultResourceLoader;

import java.util.Map;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    @Override
    public void refresh() throws BeansException {

        // 1.创建 BeanFactory,并加载 BeanDefinition
        refreshBeanFactory();

        // 2.获取 BeanFactory
        ConfigureableListableBeanFactory beanFactory =  getBeanFactory();

        // 3. 在实例化 Bean 之前，执行 beanFactory 后置增强器
        invokeBeanFactoryPostProcessors(beanFactory);

        // 4. 在实例化 Bean 之前，注册 bean 的后置增强器
        registerBeanPostProcessors(beanFactory);

        // 5. 提前实例化单例 bean
        beanFactory.preInstantiateSingletons();

    }


    protected abstract void refreshBeanFactory() throws BeansException;


    protected abstract ConfigureableListableBeanFactory getBeanFactory();


    private void invokeBeanFactoryPostProcessors(ConfigureableListableBeanFactory beanFactory){
        Map<String,BeanFactoryPostProcessor> beanFactoryPostProcessorMap = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()){
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    private void registerBeanPostProcessors(ConfigureableListableBeanFactory beanFactory){
        Map<String, BeanPostProcessor> beanPostProcessorMap =  beanFactory.getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor: beanPostProcessorMap.values()){
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return getBeanFactory().getBeansOfType(type);
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return getBeanFactory().getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return getBeanFactory().getBean(name,args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getBeanFactory().getBean(name,requiredType);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    }

    @Override
    public void close() {
        getBeanFactory().destroySingletons();
    }
}
